import { defineStore } from 'pinia'
import { createAuthWebSocket } from '@/utils/websocket'
import { listAlarm} from '@/api/farmer/alarm'

export const useWebSocketStore = defineStore('websocket', {
  state: () => ({
    websocket: null,       // 全局唯一连接实例
    isConnected: false,    // 连接状态
    messages: []           // 持久化消息列表
  }),
  actions: {
    // 建立连接
    connect(userStore) {
      // 已连接或无用户信息则返回
      if (this.isConnected || !userStore.token) return

      const role = userStore.roles?.[0] || ''
      const userId = userStore.nickName || ''
      
      if (!userId || !role) {
        this.addMessage('❌ 未获取到用户信息，无法建立连接', 'system')
        return
      }

      // 关闭旧连接
      this.close()

      // 创建新连接
      this.websocket = createAuthWebSocket(`/ws/demo/${userId}/${role}`)
      if (!this.websocket) return

      // 连接成功
      this.websocket.onopen = () => {
        this.isConnected = true
        this.addMessage(`✅ 连接成功（角色：${role}）`, 'system')
        listAlarm({
          pageNum: 1,
          pageSize: 1000,
          status: 0
        }).then(res => {
          console.log(res.rows)
          res.rows.forEach(item => {
            console.log(item)
            this.addMessage(`用蜂农出界：${item.farmerName} 电话：${item.farmerPhone} 时间：${item.alarmTime}`,'alarm')
          })
        })
      }

      // 接收消息
      this.websocket.onmessage = (event) => {
        const type = event.data.includes('⚠️') ? 'alarm' : 'system'
        this.addMessage(event.data, type)
      }

      // 连接关闭
      this.websocket.onclose = (event) => {
        this.isConnected = false
        const reason = event.wasClean ? '正常关闭' : '异常关闭'
        this.addMessage(`❌ 连接已关闭（原因：${reason}）`, 'system')
        this.websocket = null

        // 异常关闭且已登录时自动重连
        if (!event.wasClean && userStore.token) {
          setTimeout(() => this.connect(userStore), 3000)
        }
      }

      // 连接错误
      this.websocket.onerror = (error) => {
        this.isConnected = false
        this.addMessage(`❌ 连接异常：${error.message}`, 'system')
      }
    },

    // 关闭连接
    close() {
      if (this.websocket) {
        this.websocket.close(1000, '主动关闭')
        this.websocket = null
        this.isConnected = false
      }
    },

    // 添加消息
    addMessage(content, type) {
      this.messages.push({
        content,
        type,
        time: new Date().toLocaleTimeString()
      })
      // 限制最大消息数（避免内存溢出）
      if (this.messages.length > 1000) {
        this.messages.shift()
      }
    },

    // 清空消息
    clearMessages() {
      this.messages = []
    }
  }
})